package org.ims.inv.web.action.flow;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.ims.inv.model.flow.ModelFlowTemplate;
import org.ims.inv.model.flow.confer.ModelFlowConfer;
import org.ims.inv.model.project.ModelProjectProcess;
import org.ims.inv.model.system.ModelAppRole;
import org.ims.inv.service.project.ServiceProjectProcess;
import org.springframework.beans.BeanUtils;

import cn.trymore.core.log.LogAnnotation;
import cn.trymore.core.util.UtilCollection;
import cn.trymore.core.util.UtilString;

/**
 * Action: 过会审批流程
 * 
 * @author Jeccy.Zhao
 *
 */
public class FlowDefConferenceAction
extends FlowBaseAction
{
	/**
	 * The LOGGER
	 */
	private static final Logger LOGGER = Logger.getLogger(FlowDefConferenceAction.class);
	
	/**
	 * Service of project process
	 */
	private ServiceProjectProcess serviceProjectProcess;
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 过会流程页面
	 */
	public ActionForward pageFlowConferIndex (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			
			request.setAttribute("datagrid", 
					serviceWorkFlow.getServiceFlowConfer().getAll());
			
			return mapping.findForward("page.flow.def.confer.index");
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 过会流程配置弹框
	 */
	public ActionForward dialogFlowConferPage (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String entityId = request.getParameter("id");
			if (UtilString.isNotEmpty(entityId))
			{
				if (this.isObjectIdValid(entityId))
				{
					ModelFlowConfer entity = serviceWorkFlow.getServiceFlowConfer().get(entityId);
					request.setAttribute("entity", entity);
				}
				else
				{
					return ajaxPrint(response, getErrorCallback("数据ID不合法!"));
				}
			}
			
			request.setAttribute("allRoles", this.getAllRoles());
			
			return mapping.findForward("dialog.flow.def.confer");
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when loading dialog page", e);
			return ajaxPrint(response, getErrorCallback("数据加载失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 保存过会流程定义
	 */
	@LogAnnotation(description="过会审批节点新增或更新, `${nodeTitle}`",type="过会流程设置")
	public ActionForward actionSaveFlowConfer (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			ModelFlowConfer formEntity = (ModelFlowConfer) form;
			ModelFlowConfer entity = formEntity;
			
			boolean isActionEdit = this.isObjectIdValid(formEntity.getId());
			if (isActionEdit)
			{
				// 编辑
				entity = serviceWorkFlow.getServiceFlowConfer().get(formEntity.getId());
				if (entity != null)
				{
					BeanUtils.copyProperties(formEntity, entity, new String[] { "toAuditRole" } );
				}
				else
				{
					return ajaxPrint(response, getErrorCallback("数据实体不存在!"));
				}
			}
			
			// 设置审批角色
			String roleId = request.getParameter("toAuditRoleId");
			if (this.isObjectIdValid(roleId))
			{
				ModelAppRole role = this.serviceAppRole.get(roleId);
				if (role != null)
				{
					entity.setToAuditRole(role);
				}
				else
				{
					return ajaxPrint(response, getErrorCallback("审批角色不存在!"));
				}
			}
			
			serviceWorkFlow.getServiceFlowConfer().save(entity);
			
			return ajaxPrint(response, 
					getSuccessCallback("数据保存成功.", CALLBACK_TYPE_CLOSE, CURRENT_NAVTABID, null, false));
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when saving data", e);
			return ajaxPrint(response, getErrorCallback("操作失败,原因:" + e.getMessage()));
		}
	}
	
	/**
	 * <b>[WebAction]</b> 
	 * <br/>
	 * 移除过会流程定义
	 */
	@LogAnnotation(description="过会审批节点移除, `${id}`",type="过会流程设置")
	public ActionForward actionRemoveFlowConfer (ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) 
	{
		try
		{
			String entityId = request.getParameter("id");
			if (this.isObjectIdValid(entityId))
			{
				ModelFlowConfer entity = serviceWorkFlow.getServiceFlowConfer().get(entityId);
				if (entity != null)
				{
					// 解除正在运行的审批节点
					List<ModelProjectProcess> runningProcess = 
						this.serviceProjectProcess.getProcessByDependedFlow(entity.getId());
					
					if (UtilCollection.isNotEmpty(runningProcess))
					{
						for (ModelProjectProcess process : runningProcess)
						{
							process.setDependedFlow(null);
							process.setDependedFlowAuditStatus(null);
						}
					}
					
					// 解除流程模板
					ModelFlowTemplate criterion = new ModelFlowTemplate();
					criterion.setDependedFlow(entity);
					List<ModelFlowTemplate> tpls = this.serviceWorkFlow.getServiceFlowTemplate().getByCriterion(criterion);
					if (UtilCollection.isNotEmpty(tpls))
					{
						for (ModelFlowTemplate tpl : tpls)
						{
							tpl.setDependedFlow(null);
							this.serviceWorkFlow.getServiceFlowTemplate().save(tpl);
						}
					}
					
					serviceWorkFlow.getServiceFlowConfer().remove(entityId);
				}
				else
				{
					return ajaxPrint(response, getErrorCallback("数据实体不合法!"));
				}
				
				return ajaxPrint(response, 
						getSuccessCallbackAndReloadCurrent("数据删除成功."));
			}
			else
			{
				return ajaxPrint(response, getErrorCallback("数据ID不合法!"));
			}
		}
		catch (Exception e)
		{
			LOGGER.error("Exception raised when removing data", e);
			return ajaxPrint(response, getErrorCallback("数据删除失败,原因:" + e.getMessage()));
		}
	}
	
	public static Logger getLogger()
	{
		return LOGGER;
	}

	public void setServiceProjectProcess(ServiceProjectProcess serviceProjectProcess)
	{
		this.serviceProjectProcess = serviceProjectProcess;
	}

	public ServiceProjectProcess getServiceProjectProcess()
	{
		return serviceProjectProcess;
	}
		
}
